<template>
  <div>
    <a-row>
      <a-button type="primary" @click="showModal(false)">新增</a-button>
      <a-button type="primary" @click="showModal(true)">修改</a-button>
      <a-button type="danger" @click="removeVersionInfo">删除</a-button>
      <a-select @change="handleAppChange" style="width: 150px" placeholder="请选择应用">
      <a-select-option v-for="app in appList" :key="app.id">{{app.app}}</a-select-option>
    </a-select>
      <a-select v-model="versionTypeMode" @change="handleVersionChange"
                style="width: 200px" placeholder="版本">
        <a-select-option v-for="version in appVersionLinkage" :key="version.id">
          {{version.versionName}}
        </a-select-option>
      </a-select>
    </a-row>
    <a-row>
      <a-col :span="24">
        <a-table :columns="grid.columns"
                 :rowKey="record => record.id"
                 :dataSource="grid.data"
                 :pagination="grid.pagination"
                 :loading="loading"
                 @change="handleTableChange"
                 :rowSelection="grid.rowSelection"
        >
          <template slot="name" slot-scope="name">
            {{name.first}} {{name.last}}
          </template>
        </a-table>
      </a-col>
    </a-row>

    <!--新增版本-->
    <a-modal
      title="版本信息"
      :maskClosable="false"
      :visible="visible"
      @ok="handleOk"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
      :destroyOnClose="true"
    >
      <a-form :form="form">
        <a-form-item
          label="类型"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-select
            style="width: 100%" v-decorator="[
            'type',{rules: [{ required: true, message: '请选择版本类型' }]}
            ]">
            <a-select-option v-for="versionType in versionTypeList" :key="versionType.id">
              {{versionType.name}}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="创建时间"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-date-picker
            v-decorator="['createTime', config]"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
          />
        </a-form-item>
        <a-form-item
          label="版本描述"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-textarea
            v-decorator="[
          'versionDesc',
          {rules: [{ required: true, message: '请输入版本描述' }]}]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
  import AFormItem from "gov-design-vue/es/form/FormItem";
  import ATextarea from "gov-design-vue/es/input/TextArea";
  import {getFetch, postFetch} from '@/util/fetch';

  export default {
    components: {
      ATextarea,
      AFormItem
    },
    mounted() {
      this.fetch();
      this.initVersionList();
      this.initAppList();
      this.initVersionTypeList();
    },
    data() {
      return {
        versionList: [],
        appList: [],
        appIdSelected: null,
        versionIdSelected: null,
        appVersionLinkage: [],
        versionTypeMode: "请选择版本",
        versionTypeList: [],
        config: {
          rules: [{ type: 'object', required: true, message: 'Please select time!' }],
        },
        grid: {
          columns: [
            {
              title: 'ID',
              dataIndex: 'id'
            },
            {
              title: '版本描述',
              dataIndex: 'versionDesc'
            },
            {
              title: '描述类型',
              dataIndex: 'type'
            },
            {
              title: '创建时间',
              dataIndex: 'createTime'
            }
          ],
          data: [],
          selectedRows: [],
          rowSelection: {
            type: "radio",
            selectedRowKeys: [],
            onChange: this.onSelectChange,
          },
          pagination: {
            pageSize: 10,
            current: 1
          },
          params: ""
        },
        form: this.$form.createForm(this),
        loading: false,
        ModalText: 'Content of the modal',
        visible: false,
        confirmLoading: false,
        editVersionInfo: false,
      }
    },
    methods: {
      initVersionList() {
        let that = this;
        getFetch("/api/version?pageable=false").then((data) => {
          that.versionList = data.data.content;
        });
      },
      initAppList() {
        let that = this;
        getFetch("/api/app?pageable=false").then((data) => {
          that.appList = data.data.content;
        });
      },
      initVersionTypeList() {
        let versionTypeInit = ["功能", "bug", "优化"];
        for (let i = 0; i < versionTypeInit.length; i++) {
          let obj = {};
          obj.id = versionTypeInit[i];
          obj.name = versionTypeInit[i];
          this.versionTypeList.push(obj);
        }
      },
      handleAppChange(value) {
        const that = this;
        that.appIdSelected = value;
        that.appVersionLinkage = [];
        for (let i = 0; i < that.versionList.length; i++) {
          let appId = that.versionList[i].app.id;
            if (value === appId) {
              that.appVersionLinkage.push(that.versionList[i]);
            }
        }
        this.versionTypeMode = "";
        this.grid.params = "version.app.id=" + value;
        this.fetch();
      },
      handleVersionChange(value) {
        this.versionIdSelected = value;
        this.grid.params = "version.id=" + value;
        this.fetch();
      },
      removeVersionInfo() {
        if (this.grid.selectedRows.length !== 1) {
          this.$message.warn("请选中一行");
          return;
        }
        let that = this;
        this.$confirm({
          title: '确认',
          content: '你确认要删除吗?',
          onOk() {
            getFetch("/api/versionInfo/" + that.grid.selectedRows[0].id + "/delete").then((data) => {
              that.fetch();
            });
          },
          onCancel() {
          },
        });
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.grid.selectedRows = selectedRows;
        this.grid.rowSelection.selectedRowKeys = selectedRowKeys;
      },
      showModal(edit) {
        if (this.appIdSelected === null) {
          this.$message.warn("请选这应用");
          return;
        }
        if (this.appVersionLinkage.length === 0) {
          this.$message.warn("请添加版本");
          return;
        }
        if (this.versionIdSelected === null) {
          this.$message.warn("请选中版本");
          return;
        }
        if (edit) {
          this.editVersionInfo = true;
          if (this.grid.selectedRows.length !== 1) {
            this.$message.warn("请选中行");
            return;
          } else {
            let row = this.grid.selectedRows[0];
            setTimeout(() => {
              this.form.setFieldsValue({
                versionId: row.version.id,
                versionDesc: row.versionDesc,
                type: row.type,
                // createTime: row.createTime
              });
            }, 0);
          }
        } else {
          this.editVersionInfo = false;
          this.form.resetFields();
        }
        this.visible = true
      },
      handleOk(e) {
        console.log("------");
        e.preventDefault();
        const that = this;
        this.form.validateFields((err, values) => {
          if (!err) {
            if (this.editVersionInfo) {
              values.id = this.grid.selectedRows[0].id;
            }
            values.createTime = values.createTime.format('YYYY-MM-DD HH:mm:ss');
            console.log(values.createTime);
            let url = "/api/versionInfo";
            if (this.editVersionInfo) {
              url += "/update";
            }
            for (let i = 0; i < that.versionList.length; i++) {
              if (that.versionList[i].id === this.versionIdSelected) {
                values.version = that.versionList[i];
                break;
              }
            }
            postFetch(url, values).then((data) => {
              this.form.resetFields();
              this.visible = false;
              this.fetch();
              this.grid.rowSelection.selectedRowKeys = [];
              this.grid.selectedRows = [];
            });
          } else {
            this.$message.error("字段有错误");
          }
        });
      },
      handleCancel(e) {
        console.log('Clicked cancel button');
        this.visible = false;
      },
      handleTableChange(pagination, filters, sorter) {
        this.grid.pagination.current = pagination.current;
        this.grid.pagination.pageSize = pagination.pageSize;
        this.fetch();
      },
      fetch() {
        const that = this;
        that.loading = true;
        getFetch("/api/versionInfo?" + that.grid.params + "&page=" + that.grid.pagination.current + "&size=" + that.grid.pagination.pageSize).then((data) => {
          const pagination = { ...that.grid.pagination };
          pagination.total = data.data.totalElements;
          that.loading = false;
          that.grid.data = data.data.content;
          that.grid.pagination = pagination;
        });
      }
    },
  }
</script>
